package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.entity.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocal;
import com.heima.media.dto.*;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.media.service.IWmUserService;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-22
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Override
    public ResponseResult listByPage(WmNewsPageDto dto) {
//        判断用户是否登录
        User user = MediaThreadLocal.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
//        查询本用户
        query.eq(WmNews::getUserId, user.getUserId());
//        判断状态是否为空
        if (dto.getStatus() != null) {
            query.eq(WmNews::getStatus, dto.getStatus());
        }
//        判断关键字是否为空
        if (!StringUtils.isEmpty(dto.getKeyword())) {
            query.like(WmNews::getTitle, dto.getKeyword());
        }
//        判断频道是否为空
        if (dto.getChannelId() != null) {
            query.eq(WmNews::getChannelId, dto.getChannelId());
        }
//        判断开始时间
        if (dto.getBeginPubDate() != null) {
            query.ge(WmNews::getPublishTime, dto.getBeginPubDate());
        }
//        判断结束时间
        if (dto.getEndPubDate() != null) {
            query.lt(WmNews::getPublishTime, dto.getEndPubDate());
        }
//        默认发布时间排序
        query.orderByDesc(WmNews::getPublishTime);
//        分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        this.page(page, query);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
        return result;
    }

    @Autowired
    @Lazy
    private IAuditService auditService;

    @Override
    public ResponseResult submit(WmNewsDto wmNewsDto) {
//        判断是否登录
        User user = MediaThreadLocal.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }


//        判断是否存在id
        if (wmNewsDto.getId() != null) {
//        是 删除已关联的素材关系
            deleteById(wmNewsDto.getId());
        }


//        否 新增文章
        WmNews news = new WmNews();
        BeanUtils.copyProperties(wmNewsDto, news);
        news.setUserId(user.getUserId());
        news.setCreatedTime(new Date());
        List<ImageDto> images = wmNewsDto.getImages();
        news.setImages(JSON.toJSONString(images));


        List<ImageDto> list = saveContent(news.getContent());
//        自动状态
        if (wmNewsDto.getType() == -1) {
            if (list.size() == 0) {
//                没有图片，修改状态为0
                news.setType(0);
            } else if (list.size() < 3) {
//                如果图片数 小于3 大于0 取第一张图片
                news.setType(1);
                news.setImages(JSON.toJSONString(list.subList(0, 1)));
            } else {
//                如果图片数 大于 3
                news.setType(3);
                news.setImages(JSON.toJSONString(list.subList(0, 3)));
            }

        }
        this.saveOrUpdate(news);


//        判断是否为草稿
        if (wmNewsDto.getStatus() != 0) {
//        否 关联内容中的图片与素材
//        关联封面中的图片与素材的关系
//        图片添加关联关系
            List<ImageDto> imageDtos = JSON.parseArray(news.getImages(), ImageDto.class);
            saveNewsMaterial(news, imageDtos, 1);
//        内容添加关联关系
            saveNewsMaterial(news, list, 0);
//            自动审核
            System.out.println(Thread.currentThread().getName() + "开启自动审核");
            auditService.audit(news);
//            定时发布
            sendMessage(news);
        }


//        结束
        return ResponseResult.okResult("操作成功");
    }

    @Autowired
    private KafkaTemplate<String,String> template;

    @Override
    public ResponseResult changeEnable(WmNewsDto dto) {
//        根据id查询文章对象
        WmNews wmNews = this.getById(dto.getId());
//        判断文章是否存在
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        判断文章是否上架
        if (wmNews.getStatus() != 9){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
//        文章下架
        wmNews.setEnable(dto.getEnable()== 1?true:false);
//        下架
        this.updateById(wmNews);
//        同步到article
//        kafka发送消息
        String key = wmNews.getArticleId().toString();

        String value = dto.getEnable().toString();
        template.send(upDownTopic,0,key,value);
        return ResponseResult.okResult();
    }
    @Autowired
    private IWmUserService wmUserService;

    @Override
    public PageResponseResult<List<WmNewsVo>> findPageByName(NewsAuthDto dto) {
//        分页查询
        Wrapper<WmNews> query = new LambdaUpdateWrapper<>();
//        判断标题是否为空
        if (dto.getTitle() != null){
            ((LambdaUpdateWrapper<WmNews>) query).like(WmNews::getTitle,dto.getTitle());
        }
//        判断状态是否发布
        if (dto.getStatus() != null){
            ((LambdaUpdateWrapper<WmNews>) query).eq(WmNews::getStatus,dto.getStatus());
        }
//        发布时间倒序
        ((LambdaUpdateWrapper<WmNews>) query).orderByDesc(WmNews::getPublishTime);
        IPage<WmNews> page = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmNews> iPage = this.page(page, query);

        List<WmNewsVo> vos = new ArrayList<>();
        List<WmNews> records = iPage.getRecords();
        for (WmNews record : records) {
            WmNewsVo vo = new WmNewsVo();
            BeanUtils.copyProperties(record,vo);
//            查询作者
            WmUser wmUser = wmUserService.getById(record.getUserId());
            vo.setAuthorName(wmUser.getName());
            vos.add(vo);
        }
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), vos);
        return result;
    }

    @Override
    public ResponseResult<WmNewsVo> findNewsVoById(Long id) {
//        查询文章
        WmNews wmNews = this.getById(id);
        WmNewsVo vo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,vo);
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        vo.setAuthorName(wmUser.getName());
        return ResponseResult.okResult(vo);

    }

    @Override
    public ResponseResult auth(NewsAuthDto dto, int type) {
//        查询文章
        WmNews wmNews = this.getById(dto.getId());
//        如果是不通过
        if (type == 0){
//            修改状态，添加失败原因
            wmNews.setStatus(2);
            wmNews.setReason(dto.getMsg());
            this.updateById(wmNews);
        }
//        如果是通过
        if (type == 1){
            wmNews.setStatus(4);
            this.updateById(wmNews);
            auditService.audit(wmNews);
        }
        return ResponseResult.okResult();
    }

    @Value("${topic.upDownTopic}")
    private String upDownTopic;

    @Autowired
    private RedissonClient redissonClient;
    private void sendMessage(WmNews news) {
//        判断发布时间是否大于当前时间
        if (news.getPublishTime().getTime() > System.currentTimeMillis()){
            news.setStatus(8);
            this.updateById(news);
            RBlockingDeque<Object> test_msg = redissonClient.getBlockingDeque("test_msg");
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(test_msg);
            long time = news.getPublishTime().getTime() - System.currentTimeMillis();

            delayedQueue.offer(JSON.toJSONString(news),time, TimeUnit.MILLISECONDS);
        }
    }

    private void deleteById(Integer id) {
        LambdaQueryWrapper<WmNewsMaterial> query = new LambdaQueryWrapper<>();
        query.eq(WmNewsMaterial::getId, id);
        wmNewsMaterialService.remove(query);
    }

    /**
     * 内容中寻找图片
     *
     * @param content
     */
    private List<ImageDto> saveContent(String content) {
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        List<ImageDto> list = new ArrayList<>();
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("image")) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                list.add(imageDto);

            }
        }
        return list;
    }

    @Autowired
    private WmNewsMaterialServiceImpl wmNewsMaterialService;

    /**
     * 创建封面关系表
     *
     * @param news
     * @param imageDtos
     * @param i
     */
    private void saveNewsMaterial(WmNews news, List<ImageDto> imageDtos, int i) {
        int Ord = 0;
        for (ImageDto imageDto : imageDtos) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(imageDto.getId());
            wmNewsMaterial.setNewsId(news.getId());
            wmNewsMaterial.setOrd(Ord);
            wmNewsMaterial.setType(i);
            wmNewsMaterialService.save(wmNewsMaterial);
            Ord++;
        }
    }

}

